from django.shortcuts import render,redirect,HttpResponse
from  django.contrib import auth
from  django.contrib.auth.decorators import login_required
from .form import UserForm
import traceback
import json
from  .models import Project,Module,TestCase,CaseSuit,SuiteCase,InterfaceServer,TestcaseExecuteResult,CaseSuiteExecuteRecord,CaseSuiteTestCaseExecuteRecord
from django.core.paginator import Paginator,PageNotAnInteger,InvalidPage
from  .task import  case_task,suite_task
# Create your views here.
def get_paginator(request,data):
    paginator= Paginator(data,10)
    page = request.GET.get('page')
    try:
        paginator_pages= paginator.page(page)
    except PageNotAnInteger:
        paginator_pages=paginator.page(1)
    except InvalidPage:
        return  HttpResponse("找不到页面")
    return  paginator_pages
@login_required
def module(request):
    if request.method=='GET':
        modules=Module.objects.filter().order_by('-id')
        return  render(request,'module.html',{'modules':get_paginator(request,modules)})
    else:
        proj_name=request.POST['proj_name']
        projects=Project.objects.filter(name__contains=proj_name.strip())
        projs=[proj.id for proj in projects]
        modules= Module.objects.filter(belong_project__in=projs)
        return  render(request,'module.html',{'modules':get_paginator(request,modules),'proj_name':proj_name})
@login_required
def project(request):
    projects = Project.objects.filter().order_by('-id')
    return  render(request,'project.html',{'projects':projects})

def get_server_address(env):
    if env:  # 环境处理
        env_data =InterfaceServer.objects.filter(env=env[0])
        print("env_data: {}".format(env_data))
        if env_data:
            ip = env_data[0].ip
            port = env_data[0].port
            print("ip: {}, port: {}".format(ip, port))
            server_address = "http://{}:{}".format(ip, port)
            print("server_address: {}".format(server_address))
            return server_address
        else:
            return ""
    else:
        return ""

@login_required
def test_case(request):
    test_cases=""
    if request.method=="GET":
        test_cases=TestCase.objects.filter().order_by('id')
    elif request.method=="POST":
        test_case_id_list=request.POST.getlist('test_cases_list')
        env=request.POST.getlist('env')
        server_address=get_server_address(env)
        if not server_address:
            return HttpResponse("提交的运行环境为空，请选择后再提交")
        if test_case_id_list:
            test_case_id_list.sort()
            # case_task(test_case_id_list,server_address)
            case_task.app_async(test_case_id_list,server_address)
        else:
            return HttpResponse("提交的运行测试用例为空，请选择用例后在提交！")
        test_cases =TestCase.objects.filter().order_by('id')
    return  render(request,'test_case.html',{'test_cases':get_paginator(request,test_cases)})
@login_required
def test_case_detail(request,test_case_id):
    test_case_id= int(test_case_id)
    test_case = TestCase.objects.get(id=test_case_id)
    return  render(request,'test_case_detail.html',{'test_case':test_case})
@login_required
def module_test_cases(request,module_id):
    module=""
    if module_id:
        module= Module.objects.get(id=int(module_id))
    test_cases=TestCase.objects.filter(belong_module=module)
    return  render(request,'test_case.html',{'test_cases':get_paginator(request,test_cases)})
@login_required
def case_suite(request):
    if request.method=="POSt":
        count_down_time=0
        if request.POST['delay_time']:
            try:
                count_down_time=int(request.POST['delay_time'])
            except:
                print("输入的延迟时间是非数字")
        else:
            print("没有输入延迟时间")
        env=request.POST.getlist('env')
        server_address=get_server_address('env')
        if not server_address:
            return HttpResponse("提交的运行环境为空，请选择环境后再提交")
        case_suite_list=request.POST.getlist("case_suite_list")
        if case_suite_list:
            for suite_id in case_suite_list:
                test_suite=CaseSuit.objects.get(id=suite_id)
                username = request.user.username
                test_suite_record=CaseSuiteExecuteRecord.objects.create(case_suite=test_suite,run_time_interval=count_down_time,creator=username)
                # suite_task(test_suite_record,test_suite,server_address)
                suite_task.apply_async((test_suite_record,test_suite,server_address),countdown=count_down_time)
        else:
            return HttpResponse("运行的测试集合为空，请选择测试集合后再运行")
    case_suites=CaseSuit.objects.filter()
    return  render(request,'case_suite.html',{'case_suites':get_paginator(request,case_suites)})
@login_required
def add_case_in_suite(request,suite_id):
    case_suite=CaseSuit.objects.get(id=suite_id)
    test_cases = TestCase.objects.filter().order_by('id')
    if request.method=="GET":
        print("test cases:",test_cases)
    elif request.method=="POST":
        test_cases_list=request.POST.getlist('testcases_list')
        if test_cases_list:
            print("勾选用例id",test_cases_list)
            for test_case in test_cases_list:
                test_case = TestCase.objects.get(id=int(test_case))
                SuiteCase.objects.create(case_suite=case_suite,test_case=test_case)
        else:
            return HttpResponse("添加的测试用例为空，请选择用例后再添加")
    return  render(request,'add_case_in_suite.html',{'test_cases':get_paginator(request,test_cases),'case_suite':case_suite})
@login_required
def show_and_delete_case_in_suite(request,suite_id):
    case_suite = CaseSuit.objects.get(id=suite_id)
    test_cases= SuiteCase.objects.filter(case_suite=case_suite)
    if request.method=="POST":
        test_cases_list=request.POST.getlist('test_cases_list')
        if test_cases_list:
            for  test_case in test_cases_list:
                test_case=TestCase.objects.get(id=int(test_case))
                SuiteCase.objects.filter(case_suite=case_suite,test_case=test_case).first().delete()
        else:
            return HttpResponse("所选测试用例为空，请选择用例后在进行删除")
    case_suite=CaseSuit.objects.get(id=suite_id)
    return render(request,'show_and_delete_case_in_suite.html',{'test_cases':get_paginator(request,test_cases),'case_suite':case_suite})
@login_required
def test_case_execute_record(request):
    test_case_execute_records=TestcaseExecuteResult.objects.filter().order_by('-id')
    return render(request,'test_case_execute_records.html',{'test_case_execute_records':get_paginator(request,test_case_execute_records)})
@login_required
def case_result_diff(request,test_record_id):
    test_record_data= TestcaseExecuteResult.objects.get(id=test_record_id)
    present_response= test_record_data.response_data
    if present_response:
        present_response= json.dumps(json.loads(present_response),sort_keys=True,indent=4,ensure_ascii=False)
    last_time_execute_response=test_record_data.last_time_response_data
    if last_time_execute_response:
        last_time_execute_response=json.dumps(json.loads(last_time_execute_response),sort_keys=True,indent=4,ensure_ascii=False)
    return  render(request,'case_result_diff.html',locals())
@login_required
def show_exception(request,execute_id):
    test_record=TestcaseExecuteResult.objects.get(id=execute_id)
    return render(request,'show_exception.html',{'exception':test_record.exception_info})
@login_required
def case_suite_execute_record(request):
    case_suite_execute_records=CaseSuiteExecuteRecord.objects.filter().order_by('-id')
    return  render(request,'case_suite_execute_record.html',{'case_suite_execute_records':get_paginator(request,case_suite_execute_records)})

@login_required
def suite_case_execute_record(request,suite_record_id):
    case_suite_execute_record=CaseSuiteExecuteRecord.objects.get(id=suite_record_id)
    suite_case_execute_records=CaseSuiteTestCaseExecuteRecord.objects.filter(case_suite_record=case_suite_execute_record)
    return  render(request,{'suite_case_execute_records':get_paginator(request,suite_case_execute_records)})
@login_required
def suite_case_result_diff(request,suite_case_record_id):
    suite_record_data=CaseSuiteTestCaseExecuteRecord.objects.get(id=suite_case_record_id)
    present_response=suite_record_data.response_data
    if present_response:
        present_response=json.dumps(json.loads(present_response),sort_keys=True,indent=4,ensure_ascii=False)
    last_time_execute_response=suite_record_data.last_time_response_data
    if last_time_execute_response:
        last_time_execute_response=json.dumps(json.loads(last_time_execute_response),sort_keys=True,indent=4,ensure_ascii=False)
    return  render(request,'case_result_diff.html',locals())
@login_required
def suite_case_exception(request,suite_case_record_id):
    test_record=CaseSuiteTestCaseExecuteRecord.objects.get(id=suite_case_record_id)
    return render(request,'show_exception.html',{'exception_info':test_record.exception_info})
@login_required
def case_suite_statistics(request,suite_id):
    case_suite= CaseSuit.objects.get(id=suite_id)
    success_num=len(CaseSuiteExecuteRecord.objects.filter(case_suite=case_suite,test_result='成功'))
    fail_num=len(CaseSuiteExecuteRecord.objects.filter(case_suite=case_suite,test_result='失败'))
    case_suite_records=CaseSuiteExecuteRecord.objects.filter(case_suite=case_suite).order_by('-id')
    return  render(request,'case_suite_statistics.html',{'case_suite_records':get_paginator(request,case_suite_records),'success_num':success_num,'fail_num':fail_num})
@login_required
def suite_case_statistics(request,suite_id):
    success_num=len(CaseSuiteTestCaseExecuteRecord.objects.filter(case_suite_record=suite_id,execute_result='成功'))
    fail_num=len(CaseSuiteTestCaseExecuteRecord.objects.filter(case_suite_record=suite_id,execute_result='失败'))
    suite_case_records=CaseSuiteTestCaseExecuteRecord.objects.filter(case_suite_record=suite_id).order_by('-id')
    return  render(request,'suite_case_statistics.html',{'suite_case_records':get_paginator(request,suite_case_records),'success_num':success_num,'fail_num':fail_num})
@login_required
def module_statistics(request,module_id):
  test_module=Module.objects.get(id=module_id)
  test_cases=TestCase.objects.filter(belong_module=test_module)
  test_suit_success_num=len(CaseSuiteTestCaseExecuteRecord.objects.filter(test_case__in=test_cases,execute_result="成功"))
  test_suit_fail_num=len(CaseSuiteTestCaseExecuteRecord.objects.filter(test_case__in=test_cases,execute_result="失败"))
  test_case_success_num=len(TestcaseExecuteResult.objects.filter(belong_test_case__in=test_cases,execute_result="成功"))
  test_case_fail_num=len(TestcaseExecuteResult.objects.filter(belong_test_case__in=test_cases,execute_result="失败"))
  success_num=test_suit_success_num + test_case_success_num
  fail_num=test_suit_success_num+test_case_fail_num
  return  render(request,'module_statistics.html',{'test_module':test_module,'sucess_num':success_num,'fail_num':fail_num})

@login_required
def project_statistics(request,project_id):
    test_project=Project.objects.get(id=int(project_id))
    test_cases = TestCase.objects.filter(belong_project=test_project)
    test_suit_success_num= len(CaseSuiteTestCaseExecuteRecord.objects.filter(test_case__in=test_cases,execute_result="成功"))
    test_suit_fail_num = len(CaseSuiteTestCaseExecuteRecord.objects.filter(test_case__in=test_cases,execute_result="失败"))
    test_case_success_num=len(TestcaseExecuteResult.objects.filter(belong_test_case__in=test_cases,execute_result="成功"))
    test_case_fail_num = len(TestcaseExecuteResult.objects.filter(belong_test_case__in=test_cases,execute_result="失败"))
    success_num = test_suit_success_num+test_case_success_num
    fail_num = test_suit_fail_num+test_case_fail_num
    return  render(request,'project_statistics.html',{'test_project':test_project,'success_num':success_num,'fail_num':fail_num})

@login_required
def index(request):
    return  render(request,'index.html')
def login(request):
    if request.session.get('is_login',None):
        return redirect('/')
    if request.method == 'POST':
        login_form=UserForm(request.POST)
        message = '请检查填写的内容'
        if login_form.is_valid():
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            try:
                user = auth.authenticate(username=username,password=password)
                if user is not None:
                    auth.login(request,user)
                    request.session['is_login']=True
                    redirect('/')
                else:
                    message = '用户名不存在或者密码不正确'
            except:
                traceback.print_exc()
        else:
            return  render(request,'login.html',locals())
    else:
        login_form =UserForm()
        return  render(request,'login.html',locals())
def register(request):
    return  render(request,'register.html')
@login_required
def logout(request):
    auth.logout()
    request.session.flush()
    return  redirect('/login/')